package com.project.weimi.activity;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.project.weimi.R;
import com.project.weimi.application.Constant;
import com.project.weimi.entity.response.City;
import com.project.weimi.entity.response.District;
import com.project.weimi.entity.response.Province;
import com.project.weimi.entity.response.ResponseBean;
import com.project.weimi.interfaces.MyCallBack;
import com.project.weimi.utils.GsonUtil;
import com.project.weimi.utils.NetUtils;
import com.project.weimi.utils.SetClickListener;
import com.project.weimi.utils.XUtil;
import com.project.weimi.utils.XmlPullInflateUtil;
import com.project.weimi.wheel.widget.OnWheelChangedListener;
import com.project.weimi.wheel.widget.WheelView;
import com.project.weimi.wheel.widget.adapters.ArrayWheelAdapter;
import com.project.weimi.widget.ToastMessage;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

public class AddressActivity extends BaseActivity implements OnWheelChangedListener{

	private TextView tv_address;
	private ToggleButton btn_toggle;
	
	private WheelView id_province,id_city,id_district;
	private List<Province> provinceList;
	/** 所有省 */
	private String[] mProvinceDatas;
	/** key - 省 value - 市 */
	Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
	/** key - 市 values - 区 */
	Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();
	/** key - 区 values - 邮编 */
	Map<String, String> mZipcodeDatasMap = new HashMap<String, String>();
	/** 当前省的名称 */
	private String mCurrentProviceName;
	/** 当前市的名称 */
	private String mCurrentCityName;
	/** 当前区的名称 */
	private String mCurrentDistrictName;
	/** 当前区的邮编 */
	private String mCurrentZipCode;
	
	// 选中的地址
	private String selectedAddress;
	private String userPhone;
	private String mAddress;
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentViewWithBar(R.layout.activity_address, "所在地", true, "保存");
		// 获得从个人信息页面传来的年龄值
		mAddress = getIntent().getStringExtra("address");
		
		initView();
		
	}
	
	private void initView(){
		tv_address = (TextView)findViewById(R.id.tv_address);
		btn_toggle = (ToggleButton)findViewById(R.id.btn_toggle);
		
		if(!TextUtils.isEmpty(mAddress)){
			tv_address.setText(mAddress);
		}
		
		// 监听
		SetClickListener.setClickListener(listener, tv_address,bar.getRightBar());
		btn_toggle.setOnCheckedChangeListener(onCheckedChangeListener);
		
	}
	
	private OnClickListener listener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			AlertDialog dialog = null;
			
			switch (v.getId()) {
			case R.id.tv_address: // 选择地址
				View view = LayoutInflater.from(AddressActivity.this).inflate(R.layout.dialog_address_select, null);
				id_province = (WheelView) view.findViewById(R.id.id_province);
				id_city = (WheelView) view.findViewById(R.id.id_city);
				id_district = (WheelView) view.findViewById(R.id.id_district);
				// 监听
				id_province.addChangingListener(AddressActivity.this);
				id_city.addChangingListener(AddressActivity.this);
				id_district.addChangingListener(AddressActivity.this);
				initData();
				
				dialog = new AlertDialog.Builder(AddressActivity.this).setTitle("请选择区域")
						.setPositiveButton("确定", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								//Log.e("TAG", "当前选中："+mCurrentProviceName+","+mCurrentCityName+","+mCurrentDistrictName);
								
								if(id_district.getCurrentItem() == 0){
									selectedAddress = mCurrentProviceName + mCurrentCityName;
								} else {
									selectedAddress = mCurrentProviceName + mCurrentCityName + mCurrentDistrictName;
								}
								tv_address.setText(selectedAddress);
								
							}
						})
						.setNegativeButton("取消", null).setView(view).create();
				dialog.show();
						
				break;
			case R.id.right_bar: // 保存
				
				if(!NetUtils.isConnected(AddressActivity.this)){
					ToastMessage.showToast(AddressActivity.this, "网络不给力，请检查网络设置");
				} else {
					initHttp();
				}
				
				break;
			}
		}
	};
	
	private void initHttp(){
		String str = tv_address.getText().toString().trim();
		if("点击选择地址".equals(str)){
			ToastMessage.showMyToast(AddressActivity.this, "您未修改地址");
			return;
		}
		if(str.equals(mAddress)){
			ToastMessage.showMyToast(AddressActivity.this, "地址与原来保持相同，未做修改");
			finish();
			return;
		}
		
		//Log.e("TAG", "保存的地址---"+selectedAddress);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("memberId", userPhone);
		map.put("address", selectedAddress);
		
		XUtil.post(Constant.CHANGE_ADDRESS, map, new MyCallBack<String>(){
			
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				
				if(null != result && !"".equals(result)){
					//Log.e("TAG", "AddressActivity==="+result);
					ResponseBean bean = (ResponseBean) GsonUtil.jsonToBean(
							result, ResponseBean.class);
					if(null != bean){
						String str = bean.getResult();
						if(!TextUtils.isEmpty(str) && "1".equals(str)){
							ToastMessage.showMyToast(AddressActivity.this, "修改成功");
							Intent intent = new Intent();
							intent.putExtra("address", selectedAddress);
							setResult(4, intent);
							finish();
						}
					}
				}
			}
			
			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				super.onError(ex, isOnCallback);
			}
		});
	}
	
	@Override
	public void onChanged(WheelView wheel, int oldValue, int newValue) {
		if(wheel == id_province){
			updateCities();
		}else if(wheel == id_city){
			updateAreas();
		}else if(wheel == id_district){
			mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
			mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
		}
	}
	
	private OnCheckedChangeListener onCheckedChangeListener = new OnCheckedChangeListener() {
		
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			if(isChecked){
				ToastMessage.showMyToast(AddressActivity.this, "已开启");
			}else{
				ToastMessage.showMyToast(AddressActivity.this, "已关闭");
			}
		}
	};
	
	private void initData(){
		InputStream is = null;
		try {
			is = getAssets().open("province_data.xml");
			if(is != null){
				provinceList = XmlPullInflateUtil.xmlPullInflate(is);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
//		String result = null;
//		for(Province p : list){
//			result += p.toString();
//		}
		// 初始化默认选中的省、市、区
		if(provinceList != null && !provinceList.isEmpty()){
			mCurrentProviceName = provinceList.get(0).getName();
			List<City> cityList = provinceList.get(0).getCityList();
			if(cityList != null && !cityList.isEmpty()){
				mCurrentCityName = cityList.get(0).getName();
				List<District> districtList = cityList.get(0).getDistrictList();
				mCurrentDistrictName = districtList.get(0).getName();
				mCurrentZipCode = districtList.get(0).getZipcode();
			}
		}
		
		mProvinceDatas = new String[provinceList.size()];
		for (int i = 0; i < provinceList.size(); i++) {
			// 遍历所有省
			mProvinceDatas[i] = provinceList.get(i).getName();
			List<City> cityList = provinceList.get(i).getCityList();
			String[] cityNames = new String[cityList.size()];
			for (int j = 0; j < cityList.size(); j++) {
				// 遍历省下面的市
				cityNames[j] = cityList.get(j).getName();
				List<District> districtList = cityList.get(j).getDistrictList();
				String[] districtNameArray = new String[districtList.size()];
				//District[] districtArray = new District[districtList.size()];
				for (int k = 0; k < districtList.size(); k++) {
					// 遍历市下面的区/县
					districtNameArray[k] = districtList.get(k).getName();
					//District district = new District(districtList.get(k).getName(), districtList.get(k).getZipcode());
					// 将区/县对应的邮编保存到集合
					mZipcodeDatasMap.put(districtList.get(k).getName(), districtList.get(k).getZipcode());
					//districtArray[k] = district;
					//districtNameArray[k] = district.getName();
					//183,187,190,191
				}
				// 将市-区/县的数据，保存到集合
				mDistrictDatasMap.put(cityNames[j], districtNameArray);
			}
			// 将省-市的数据，保存到集合
			mCitisDatasMap.put(provinceList.get(i).getName(), cityNames);
		}
		
		id_province.setViewAdapter(new ArrayWheelAdapter<String>(AddressActivity.this, mProvinceDatas));
		// 设置可见条目数量
		id_province.setVisibleItems(7);
		id_city.setVisibleItems(7);
		id_district.setVisibleItems(7);
		updateCities();
		updateAreas();
	}
	
	/**
	 * 根据当前的省，更新市WheelView的信息
	 */
	private void updateCities() {
		int pCurrent = id_province.getCurrentItem();
		mCurrentProviceName = mProvinceDatas[pCurrent];
		String[] cities = mCitisDatasMap.get(mCurrentProviceName);
		if(cities == null){
			cities = new String[] { "" };
		}
		id_city.setViewAdapter(new ArrayWheelAdapter<String>(AddressActivity.this, cities));
		id_city.setCurrentItem(0);
		updateAreas();
	}
	
	/**
	 * 根据当前的市，更新县区WheelView的信息
	 */
	private void updateAreas() {
		int pCurrent = id_city.getCurrentItem();
		mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
		String areas[] = mDistrictDatasMap.get(mCurrentCityName);
		if(areas == null){
			areas = new String[] { "" };
		}
		id_district.setViewAdapter(new ArrayWheelAdapter<String>(AddressActivity.this, areas));
		id_district.setCurrentItem(0);
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		if(null != spHelper && !TextUtils.isEmpty(memberId)){
			//Log.e("TAG", "onStart----AddressActivity前memberId===---"+memberId);
			userPhone = memberId;
			//Log.e("TAG", "onStart----AddressActivity后userPhone===---"+userPhone);
		}
	}
	
	@Override
	void setStatusBar(int statusBarColorRes) {
		super.setStatusBar(R.color.transparent_3);
	}
	
}
